package cn.iocoder.yudao.module.system.controller.admin.warehouse;// cn/iocoder/yudao/module/gold/controller/admin/transfer/GoldMaterialTransferController.java

import cn.iocoder.yudao.framework.common.pojo.CommonResult;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.module.system.controller.admin.warehouse.vo.*;
import cn.iocoder.yudao.module.system.dal.dataobject.warehouse.GoldMaterialTransferDO;
import cn.iocoder.yudao.module.system.dal.dataobject.warehouse.GoldMaterialWarehouseDO;
import cn.iocoder.yudao.module.system.dal.mysql.warehouse.GoldMaterialTransferMapper;
import cn.iocoder.yudao.module.system.dal.mysql.warehouse.GoldMaterialWarehouseMapper;
import cn.iocoder.yudao.module.system.dal.mysql.warehouse.GoldMaterialRecordMapper;
import cn.iocoder.yudao.module.system.dal.dataobject.warehouse.GoldMaterialRecordDO;
import cn.iocoder.yudao.module.system.enums.GoldOperationTypeEnum;
import cn.iocoder.yudao.module.system.service.warehouse.GoldMaterialTransferService;
import io.swagger.v3.oas.annotations.Operation;
import com.mzt.logapi.starter.annotation.LogRecord;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.*;

@RestController
@RequestMapping("/gold/material/transfer")
public class GoldMaterialTransferController {

    @Resource
    private GoldMaterialTransferService service;
    @Resource
    private GoldMaterialWarehouseMapper warehouseMapper;
    @Resource
    private GoldMaterialTransferMapper transferMapper;
    @Resource
    private GoldMaterialRecordMapper recordMapper;

    // 原来的统一创建接口（可以保留或删除）
    @PostMapping("/create")
    @PreAuthorize("@ss.hasPermission('gold:material-transfer:create')")
    @LogRecord(type = "金料调拨", subType = "创建记录", bizNo = "{{#reqVO.fromWarehouseId}}", 
               extra = "{{#reqVO}}", success = "创建调拨记录成功")
    public CommonResult<Long> create(@Valid @RequestBody TransferCreateReqVO reqVO) {
        return success(service.create(reqVO, getLoginUserId(), getLoginUserNickname()));
    }

    // 新增：调拨接口
    @PostMapping("/transfer")
    @PreAuthorize("@ss.hasPermission('gold:material-transfer:transfer')")
    @LogRecord(type = "金料调拨", subType = "调拨", bizNo = "{{#reqVO.fromWarehouseId}}", 
               extra = "{{#reqVO}}", success = "调拨成功")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<Long> transfer(@Valid @RequestBody TransferCreateReqVO reqVO) {
        ///return success(service.transfer(reqVO, getLoginUserId(), getLoginUserNickname()));
        return success(service.create(reqVO, getLoginUserId(), getLoginUserNickname()));
    }

    // 新增：派发接口
    @PostMapping("/dispatch")
    @PreAuthorize("@ss.hasPermission('gold:material-transfer:dispatch')")
    @LogRecord(type = "金料调拨", subType = "派发", bizNo = "{{#reqVO.fromWarehouseId}}", success = "派发成功")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<Long> dispatch(@Valid @RequestBody TransferCreateReqVO reqVO) {
        //return success(service.dispatch(reqVO, getLoginUserId(), getLoginUserNickname()));
        return success(service.create(reqVO, getLoginUserId(), getLoginUserNickname()));
    }

    // 新增：还料接口
    @PostMapping("/return")
    @PreAuthorize("@ss.hasPermission('gold:material-record:return')")
    @LogRecord(type = "金料调拨", subType = "还料", bizNo = "{{#reqVO.fromWarehouseId}}", success = "还料成功")
    public CommonResult<Long> returns (@Valid @RequestBody TransferCreateReqVO reqVO) {
        return success(service.create(reqVO, getLoginUserId(), getLoginUserNickname()));
    }

    @PutMapping("/approve")
    @PreAuthorize("@ss.hasPermission('gold:material-transfer:approve')")
    @LogRecord(type = "金料调拨", subType = "审核", bizNo = "{{#reqVO.id}}", success = "审核成功")
    public CommonResult<Boolean> approve(@Valid @RequestBody TransferApproveReqVO reqVO) {
        service.approve(reqVO, getLoginUserId(), getLoginUserNickname());
        return success(true);
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询调拨记录")
    //@PreAuthorize("@ss.hasPermission('gold:material-transfer:query')")
    public CommonResult<PageResult<GoldMaterialTransferRespVO>> getTransferPage(@Valid GoldMaterialTransferPageReqVO reqVO) {
        reqVO.setApproverId(getLoginUser().getId());
        PageResult<GoldMaterialTransferDO> pageResult = service.getTransferPage(reqVO);

        // 转换为RespVO
        List<GoldMaterialTransferRespVO> respList = pageResult.getList().stream()
                .map(transfer -> convertToRespVO(transfer))
                .collect(Collectors.toList());

        PageResult<GoldMaterialTransferRespVO> respPageResult = new PageResult<>(respList, pageResult.getTotal());
        return success(respPageResult);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取调拨详情")
    //@PreAuthorize("@ss.hasPermission('gold:material-transfer:query')")
    public CommonResult<GoldMaterialTransferRespVO> getTransfer(@PathVariable Long id) {
        GoldMaterialTransferDO transfer = transferMapper.selectById(id);
        if (transfer == null) {
            return null;
        }
        return success(convertToRespVO(transfer));
    }


    /**
     * 转换为响应VO
     */
    public GoldMaterialTransferRespVO convertToRespVO(GoldMaterialTransferDO transfer) {
        GoldMaterialTransferRespVO respVO = new GoldMaterialTransferRespVO();
        respVO.setId(transfer.getId());
        respVO.setTransferNo(transfer.getTransferNo());
        respVO.setTransferType(transfer.getTransferType());
        respVO.setFromWarehouseId(transfer.getFromWarehouseId());
        respVO.setToWarehouseId(transfer.getToWarehouseId());
        respVO.setTransferWeight(transfer.getTransferWeight());
        respVO.setTransferReason(transfer.getTransferReason());
        respVO.setStatus(transfer.getStatus());
        respVO.setApproverId(transfer.getApproverId());
        respVO.setApproveTime(transfer.getApproveTime());
        respVO.setApproveRemark(transfer.getApproveRemark());
        respVO.setCreateTime(transfer.getCreateTime());
        respVO.setUpdateTime(transfer.getUpdateTime());
        respVO.setAttachmentUrl(transfer.getAttachmentUrl());
        respVO.setCreator(transfer.getCreator());

        // 设置关联信息
        if (transfer.getFromWarehouseId() != null) {
            GoldMaterialWarehouseDO fromWarehouse = warehouseMapper.selectById(transfer.getFromWarehouseId());
            if (fromWarehouse != null) {
                respVO.setFromWarehouseName(fromWarehouse.getName());
            }
        }

        if (transfer.getToWarehouseId() != null) {
            GoldMaterialWarehouseDO toWarehouse = warehouseMapper.selectById(transfer.getToWarehouseId());
            if (toWarehouse != null) {
                respVO.setToWarehouseName(toWarehouse.getName());
            }
        }

        return respVO;
    }
}